Buttons and switches come in various shapes and sizes. We will use these simple 'momentary' buttons which fit nicely in a breadboard.
Connect the button to a breadboard as follows:
Circuit | Pico |
---|---|
Red | 3V3 |
Blue | GP18 or another GP pin |
Write this code and download to the Pico. The output will change according to whether the button is pressed or not.
See code on github# Test button input (button connected to 3V3)
import board
from digitalio import DigitalInOut, Direction, Pull
import time
# Set up the button on pin 18 as a digital input pin
switch = DigitalInOut(board.GP18)
switch.direction = Direction.INPUT
switch.pull = Pull.DOWN # Pull down so button value is True when pressed
# Show the button status (True is pressed, False is not pressed)
while True:
print(switch.value)
time.sleep(0.01)
The above circuit and code uses the "pull down" approach, where the pin defaults to 0 (False) when not pressed and changes to 1 (True) when the button is pressed and the connection to 3V3 is made.
An alternative is the "pull up" approach, where the pin defaults to 1 (True) when not pressed and changes to 0 (False) when the button is pressed and the connection to GND is made. This approach is explained below.
Connect the button to a breadboard as follows:
Circuit | Pico |
---|---|
Black | GND |
Blue | GP18 or another GP pin |
Write this code and download to the Pico. The output will change according to whether the button is pressed or not.
# Test button input (button connected to ground)
import board
from digitalio import DigitalInOut, Direction, Pull
import time
# Set up the button on pin 18 as a digital input pin
switch = DigitalInOut(board.GP18)
switch.direction = Direction.INPUT
switch.pull = Pull.UP # Pull up so button value is True when not pressed
# Show the button status (False is pressed, True is not pressed)
while True:
print(switch.value)
time.sleep(0.01)